import styles from './index.module.scss'
import logo from '@/assets/logo.png'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'

// 导入action
import { login } from '@/store/actions/login'

// 登录页面
export const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()

  // 获取redux中的token
  const token = useSelector(state => state.login)
  console.log('获取到的token', token)

  const onFinish = async values => {
    try {
      // 发起登录请求action
      await dispatch(login(values.mobile, values.code))
      // console.log('after dispatch');
      // 登录成功跳转到首页
      // console.log('location state', history.location.state)
      history.replace(history.location.state ? history.location.state.from : '/home')
    } catch (error) {
      console.dir(error)
      message.warn('登录错误')
    }
  }

  // const onFinishFailed = errorInfo => {
  //   console.log('Failed:', errorInfo)
  // }
  return (
    <div className={styles.login}>
      <Card
        className="geek-card"
        bordered={false}
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center'
        }}
      >
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          validateTrigger={['onBlur', 'onChange']}
          name="basic"
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            remember: true
          }}
          autoComplete="off"
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对'
              },
              { required: true, message: '请输入手机号' }
            ]}
          >
            <Input size="large" placeholder="请输入手机号" maxLength={11} />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { len: 6, message: '验证码6个字符' },
              { required: true, message: '请输入验证码' }
            ]}
          >
            <Input size="large" placeholder="请输入验证码" maxLength={6} />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked">
            <Checkbox style={{ color: '#1890ff' }}>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              style={{
                width: '100%'
              }}
            >
              登 录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
